import {
  requestDelete,
  requestGet,
  requestPost,
  requestPut
} from '../../utils/request'
import REQUEST_KEY from '../../config/request'
import { typeOf } from '../../utils/verification'

/**
 * 获取表格数据（该接口有BaseTable组件调用）
 * @param url 请求地址
 * @param params 请求参数
 * @returns {string}
 */
export function getTableData (url = '', paramObj = {}, requestM = 'post', pageParams = true) {
  let { page, rows } = paramObj
  if (typeOf(page) === 'undefined') {
    page = ''
  }
  if (typeOf(rows) === 'undefined') {
    rows = ''
  }
  const params = {}
  params.pageNum = page
  params.pageSize = rows
  Object.keys(paramObj).forEach((item) => {
    if (item !== 'page' && item !== 'rows' && paramObj[item] !== '') {
      params[item] = paramObj[item]
    }
  })
  if (pageParams) {
    if (requestM === 'post') {
      return requestPost(`${url}`, params, REQUEST_KEY.requestMode.json, REQUEST_KEY.responseType.json, { isError: true })
    }
    return requestGet(`${url}`, params, REQUEST_KEY.responseType.json, { isError: true })
  } else {
    return requestGet(`${url}`, params, REQUEST_KEY.responseType.json, { isError: true })
  }
}

/**
 * 根据id删除数据
 * @param url 请求地址
 * @param pk pk
 */
export function deleteTableByPk (url = '', pk = 0) {
  return requestDelete(`${url}/${pk}`)
}

/**
 * 新增数据
 * @param url 请求地址
 * @param params 请求参数
 * @param mode 请求方式，默认formData
 * @returns {*}
 */
export function createTableData (url, params, mode = REQUEST_KEY.requestMode.json) {
  const data = {}
  Object.keys(params).forEach((item) => {
    if (typeOf(params[item]) !== 'undefined') {
      data[item] = params[item]
    }
  })
  return requestPost(url, data, mode)
}

/**
 * 更新数据
 * @param url
 * @param params
 * @param mode
 * @returns {*}
 */
export function updateTableData (url, params, mode = REQUEST_KEY.requestMode.json) {
  const data = {}
  Object.keys(params).forEach((item) => {
    if (typeOf(params[item]) !== 'undefined') {
      data[item] = params[item]
    }
  })
  return requestPut(url, data, mode)
}

/**
 * 更新数据
 * @param url
 * @param params
 * @param ignore
 * @param mode
 * @returns {*}
 */
export function updateTableDataWithEmptyValue (url, params, ignore, mode = REQUEST_KEY.requestMode.json) {
  const data = {}
  Object.keys(params).forEach((item) => {
    if (typeOf(params[item]) !== 'undefined') {
      data[item] = params[item]
    }
    if (typeOf(ignore) === 'array' && ignore.length > 0) {
      if (params[item] === '') {
        ignore.forEach((itemChild) => {
          if (itemChild === item) {
            data[item] = params[item]
          }
        })
      }
    }
  })
  return requestPut(url, data, mode)
}

/**
 * 根据id获取详情
 * @param url
 * @param pk
 * @returns {*}
 */
export function getTableDataByoPk (url, pk) {
  return requestGet(`${url}/${pk}`, {})
}
